<template>
    <template v-if="PermissionEnum.POLICE_AREA_DROP.includes(userPost)">
        <el-tree-select
            v-model="selectedUnitId"
            :data="selectedUnitList"
            default-expand-all
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="选择单位"
            check-strictly
            @node-click="nodeClickHandle"
            style="width: 15rem;margin-bottom: 1rem"
        />
    </template>
    <el-card body-style="padding: 0 !important" style="margin-bottom: 1.375rem">

        <el-card
            shadow="never"
            v-for="(item,index) in policeSituationList"
            :key="index"
            class="police-situation-item"
        >
            <!--  {{ item }}-->
            <template #header>
                <div class="police-user">
                    <div class="department-personnel">
                        <span>{{ item.basePolicearea.areaname }}</span>
                        <span>值班领导：{{ formatUserName(policeUserList[item.basePolicearea.policeareaId], 1) }}</span>
                        <span>值班人员：{{ formatUserName(policeUserList[item.basePolicearea.policeareaId], 0) }}</span>
                    </div>
                    <div class="handles">
                        <el-button
                            type="primary"
                            size="small"
                            :disabled="!item.isShowStart"
                            @click="changeScheduleStatus(index,item.basePolicearea.policeareaId,1)"
                        >开始执勤
                        </el-button>
                        <el-button
                            type="danger"
                            size="small"
                            :disabled="!item.isShowEnd"
                            @click="changeScheduleStatus(index,item.basePolicearea.policeareaId,0)"
                        >结束执勤
                        </el-button>
                    </div>
                </div>
            </template>
            <div class="room-list">
                <div class="room-list-item"
                     v-for="row in item.baseRoomList"
                     :key="row.caseByInquestId"
                     :class="(row.isUsing || row.roomName.includes('法警值班室'))?'using':''"
                >
                    <el-card
                        shadow="never"
                        :body-class="(row.isUsing||row.roomName.includes('法警值班室'))?'':'isNoVideo'"
                    >
                        <div class="room-info">
                            <div class="room-header">
                                <el-button
                                    :icon="VideoCameraFilled"
                                    type="primary"
                                    class="room-video-icon"
                                    v-if="(row.isUsing||row.roomName.includes('法警值班室'))"
                                    @click="handleVideo(row)"
                                />
                                <div class="room-title">{{ row.roomName }}</div>
                            </div>
                            <div class="room-body">
                                <div class="status">{{
                                        row.roomName.includes('法警值班室') ? policeUserList[item.basePolicearea.policeareaId]?.onDutyUsers.map(item => item.userName).join('、') : row.isUsing ? `涉案人：${row.userName}` : '空闲中'
                                    }}
                                </div>
                            </div>
                        </div>
                        <!--                        <template #footer v-if="(row.isUsing||row.roomName.includes('法警值班室'))">-->
                        <!--                            <div class="room-list-footer">-->
                        <!--                                <el-button type="primary" size="small" link>查看监控</el-button>-->
                        <!--                            </div>-->
                        <!--                        </template>-->
                    </el-card>
                </div>

            </div>
        </el-card>

    </el-card>
    <OtherDutyBailiff :unitId="UnitId"/>
</template>

<script setup>
import useUserStore from "@/store/modules/user.js";
import {
    endPoliceSituationApi,
    getCurrentPoliceUserApi,
    getPoliceSituationApi,
    startPoliceSituationApi
} from "@/api/Schedule/Schedule.js";
import {ElMessageBox} from "element-plus";
import {deptTreeSelectPost, getUserProfile} from "@/api/system/user.js";
import {PermissionEnum} from "@/enum/PermissionEnum.js";
import OtherDutyBailiff from "@/components/PoliceAreaChart/OtherDutyBailiff.vue";
import {VideoCameraFilled} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";

const userStore = useUserStore()
// console.log(userStore.info)
const UnitId = ref(userStore.info.unitId);

// 警务状况列表数据
const policeSituationList = ref([])
const policeUserList = ref({})

// 当前选择的单位
const selectedUnitId = ref(userStore.info.curUnitId)
// 单位数据
const selectedUnitList = ref([])

// 获取警务状况图
const getPoliceSituation = async () => {
    const res = await getPoliceSituationApi(UnitId.value)
    policeSituationList.value = res.data;
    res.data.map(async (item) => {
        const res = await getCurrentPoliceUserApi(item.basePolicearea.policeareaId);
        if (res?.data) {
            policeUserList.value[item.basePolicearea.policeareaId] = res.data;
        }
    })
}

const userPost = ref('')

onMounted(async () => {
    await getPoliceSituation()
    const res = await getUserProfile()
    userPost.value = res.postGroup;
    if (PermissionEnum.POLICE_AREA_DROP.includes(res.postGroup)) {
        await getUnitTree()
    }
})

// 执勤状态变更,type 变更类型，1：开始，0：结束
const changeScheduleStatus = async (index, policeAreaId, type = 1) => {
    // type ? await startPoliceSituationApi(policeAreaId) : await endPoliceSituationApi(policeAreaId);
    //
    // // const isType = type ? 'isShowStart' : 'isShowEnd';
    // // policeSituationList.value[index][isType] = !policeSituationList.value[index][isType];
    // await getPoliceSituation()

    if (type) {
        await startPoliceSituationApi(policeAreaId);
        await getPoliceSituation();
    } else {
        ElMessageBox.prompt('执勤备注', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        })
            .then(async ({value}) => {
                await endPoliceSituationApi(policeAreaId, value);
                await getPoliceSituation()
            })
            .catch(() => {
            })
    }
}

// 优化用户名展示，1：值班领导，0：值班人员
const formatUserName = (data, type) => {
    if (!data) return '暂无';

    if (type) {
        return data.leaderName;
    }

    const leaderId = Number(data.leaderId);

    return data.onDutyUsers.filter(item => item.user_id !== leaderId).map(item => item.userName).join('、')
}

// 获取单位树
const getUnitTree = async () => {
    const res = await deptTreeSelectPost({
        isUnit: true
    });
    selectedUnitList.value = res.data
}

// 单位数选择
const nodeClickHandle = async (data, node, e) => {
    const {id} = data;
    UnitId.value = id;
    await getPoliceSituation()
}
const router = useRouter()
// 跳转监控视频页面
const handleVideo = (row) => {
    router.push({
        name: 'review',
        query: {
            roomId: row.roomId
        }
    });
}
</script>

<style scoped lang="scss">
:deep(.el-card__body) {
    padding: 15px !important;
}

.police-situation-item {
    border-radius: 0;
    border: 0;
    border-top: 1px solid var(--el-card-border-color);
}

.police-user {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .department-personnel {
        display: flex;
        //display: grid;
        //grid-template-columns: repeat(3, minmax(0, 1fr));
        //gap: 50px;
        font-size: 14px;
        line-height: 22px;

        > span {
            margin-right: 20px;
        }
    }

    .handles {
    }
}

.room-list {
    display: grid;
    grid-template-columns: repeat(5, minmax(0, 1fr));
    gap: 10px;

    .room-list-footer {
        display: flex;
        justify-content: center;
    }
}

:deep(.police-situation-item .el-card__header) {
    background: var(--el-color-primary-light-9);
    padding-top: 7px !important;
}

:deep(.room-list-item .el-card__footer) {
    padding: 10px var(--el-card-padding);
}

.room-list-item {
    position: relative;
}

:deep(.isNoVideo) {
    display: flex;
    height: 100%;
    flex-direction: column;
    justify-content: center;
}

.room-info {
    .room-header {
        display: flex;
        flex-direction: column;
        font-size: 14px;
        line-height: 22px;
        align-items: center;


        .room-video-icon {
            //--ab: 5px;
            //position: absolute;
            //left: var(--ab);
            //top: var(--ab);
        }

        .room-title {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }

    .room-body {
        display: flex;
        height: 100%;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        line-height: 22px;
    }
}

:deep(.room-list-item .el-card) {
    --el-card-border-color: var(--el-color-primary-light-9);
    --el-card-bg-color: var(--el-color-primary-light-9);
    height: 100%;
}

:deep(.room-list-item.using .el-card) {
    --el-card-border-color: var(--el-color-primary-light-6);
    --el-card-bg-color: var(--el-color-primary-light-8);
}

</style>